package com.lw.lost.adapters

import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.lw.lost.R
import com.lw.lost.activity.UserDetailActivity
import com.lw.lost.databinding.ItemRecommendUserBinding
import com.lw.lost.models.RecommendUser

class RecommendUserAdapter : ListAdapter<RecommendUser, RecommendUserAdapter.ViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemRecommendUserBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class ViewHolder(
        private val binding: ItemRecommendUserBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(user: RecommendUser) {
            binding.apply {
                tvName.text = user.name
                tvInfo.text = user.info
                tvInterests.text = user.interests
                tvMatchRate.text = user.matchRate

                // 加载头像
                Glide.with(ivAvatar)
                    .load(user.avatar)
                    .circleCrop()  // 添加圆形裁剪
                    .placeholder(R.drawable.ic_avatar_default)
                    .error(R.drawable.ic_avatar_default)
                    .into(ivAvatar)

                // 添加点击事件
                root.setOnClickListener {
                    val intent = Intent(root.context, UserDetailActivity::class.java)
                    intent.putExtra("userId", user.userId)
                    root.context.startActivity(intent)
                }
            }
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<RecommendUser>() {
        override fun areItemsTheSame(oldItem: RecommendUser, newItem: RecommendUser) =
            oldItem.userId == newItem.userId

        override fun areContentsTheSame(oldItem: RecommendUser, newItem: RecommendUser) =
            oldItem == newItem
    }
} 